var 
  http = require('http'),
  https = require('https'),
  urlParse = require('url').parse,
  logger = require('log4js').getLogger();

var _USER_AGENT_ = 'Node Monitor Agent';



var detect = function(options, callback){
  var url = urlParse(options.url);
  
  var reqOpts = {
    host: url.host,
    hostname: url.host,
    method: options.method || 'GET',
    path: url.path,
    keepAlive: false,
    agent: null
  };

  var runner = (url.protocol == 'https:')?https:http;
  if(!url.port){
    if(url.protocol == 'https:'){
      reqOpts.port = 443;  
    }else{
      reqOpts.port = 80;
    }
  }else{
    reqOpts.port = url.port;
  }


  var times = {};
  times.start = Date.now();

  var headers = {};
  var code = 200;

  var responsed = false;

  var req = runner.request(reqOpts, function (res) {
    responsed = true;
    headers = res.headers;
    code = res.statusCode;
    var hasRead = false;

    res.on('data', function (chunk) {
      // console.log(chunk.toString());
      if(!hasRead){
        times.read = Date.now();
        hasRead = true;
      }
    });

    res.on('end', function(){
      times.end = Date.now();

      callback({
        timeout: { cto: !!times.ctotime, rto: !!times.rtotime },
        times: times,
        result:{  
          headers: headers,
          code: code
        }
      });
    });  
  });

  req.on('error', function(error){
    var em = !!times.ctotime?'Connection Timeout':'';
    callback({
      error: em || error.message,
      timeout: { cto: !!times.ctotime, rto: !!times.rtotime },
      times: times
    });
  });



  req.on('socket', function(socket) {
    times.connected = Date.now();

    socket.setTimeout(options.timeout, function(){
      if(!responsed){
        times.ctotime = Date.now();
        socket.destroy();
        logger.error('Connect Timeout: [%s] : %d',options.url, times.ctotime - times.start);      
      }else{
        times.rtotime = Date.now();
        socket.destroy();
        logger.error('Read Timeout: [%s] : %d',options.url, times.rtotime - times.start);         
      }

    });

  });  
  req.end();


};




exports.detect = detect;